"""
行列操作
"""
import math

import lark_oapi as lark
from common.client import get_client
from common.enum import Dimension
from spreadsheet import data
from spreadsheet.sheets import query as query_sheet

def clear(spreadsheet_token,sheet_title):
    # 先清理所有的行列数据
    sheet = query_sheet(spreadsheet_token,sheet_title)
    row_count = sheet.grid_properties.row_count
    column_count = sheet.grid_properties.column_count
    # 采用空数据填充
    lst = []
    for i in range(1, row_count + 1):
        sub_lst = []
        for j in range(1, column_count + 1):
            sub_lst.append('')
        lst.append(sub_lst)

    data.__do_over_data(spreadsheet_token,sheet.title, lst)


def delete(spreadsheet_token,sheet_id,dimension : Dimension, start_index, end_index):
    """
    删除行或列
    :param spreadsheet_token: 表格Token
    :param sheet_id: 工作表ID
    :param dimension: 行或列
    :param start_index: 开始索引
    :param end_index: 结束索引
    """
    if start_index < 1 or end_index < 1:
        raise RuntimeError("索引不能小于1")
    if end_index < start_index:
        raise RuntimeError("结束索引不能小于开始索引")

    client = get_client()
    uri = f"/open-apis/sheets/v2/spreadsheets/{spreadsheet_token}/dimension_range"
    # 这里最多只能删除5000 或列 所以大于5000行需要多次删除
    count = end_index - start_index
    time = math.ceil(count / 5000)
    # 求余
    surplus = count % 5000

    for i in range(time if time > 0 else 1):
        param = {
                "dimension":{
                "sheetId":sheet_id,
                "majorDimension":dimension.value,
                "startIndex":start_index,
                "endIndex":start_index + surplus if i >= time -1 else start_index + 4999
            }
        }
        print(f"正在删除数据,类型{dimension.value}，范围: {param['dimension']['startIndex'] + 5000 * i } -{5000 * i + param['dimension']['endIndex']}")
        request: lark.BaseRequest = lark.BaseRequest.builder() \
            .http_method(lark.HttpMethod.DELETE) \
            .uri(uri) \
            .token_types({lark.AccessTokenType.TENANT}) \
            .body(param) \
            .build()

        response: lark.BaseResponse = client.request(request)
        if not response.success():
            raise RuntimeError(f"删除行列失败,失败原因:{response.msg}")
